<?php
declare (strict_types=1);

namespace app\common\model;


use app\common\facade\Pay;
use app\common\tool\account\Account;
use app\common\model\Account as AccountModel;
use think\facade\Event;

/**
 * 视频会员订单
 * Class Video
 * @package app\common\model
 */
class OrderVideo extends Base
{
    protected $name = 'order_video';

    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'id')->field('id,code,nickname,mobile');
    }

    public function level()
    {
        return $this->belongsTo(UserLevelVideo::class, 'level_video_id', 'id')->field('id,title');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getPayTimeAttr($value)
    {
        return $value ? date("Y-m-d H:i:s", $value) : '';
    }

    public static function payment($param, $user) :array
    {
        try{
            $account = $param['pay_way'];

            $red_coin = 0;
            $max_red_coin = UserLevelVideo::where('id',$param['level_video_id'])->value('max_red_coin');

            if($before = self::where(['uid'=>$user->id,'status'=>1])->order('create_time', 'desc')->find()){
                $red_coin = $before->red_coin;
                $max_red_coin += $before->max_red_coin;
            }

            $info = self::create([
                'uid' => $user->id,
                'sn' => date('Ymd') . $user->id . time(),
                'real_amount' => round($param['real_amount'],2),
                'level_video_id' => $param['level_video_id'],
                'max_red_coin' => $max_red_coin,
                'red_coin' => $red_coin,
            ]);

            $info->save();

            switch ($account) {
                case "alipay":
                    $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/time/callback/videoAlipay';
                    //设置参数
                    $pay = Pay::setDriver('AliPay')
                        ->basic('购买视频会员', $info->sn, $info->real_amount, $notifyUrl);
                    $options = $pay->create('App');

                    $data['pay_alipay'] = $options;
                    $data['pay_wechat'] = null;
                    return ['code' => 1, 'msg' => 'success', 'data' => $data];
                case "wechat":
                    if (!isset($param['method']) || !in_array($param['method'], ['JSAPI', 'APP'])) {
                        return ['code' => -1, 'msg' => '支付标识不存在'];
                    }
                    $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/time/callback/videoWechat';
                    //设置参数
                    $wechat_pay = Pay::setDriver('WeChat')
                        ->basic('购买视频会员', $info->sn, $info->real_amount, $notifyUrl)
                        ->setMerchantType('mall');
                    if ($param['method'] == 'JSAPI') {
                        $wechat_pay->setOpenId($user->openid);
                    }
                    $options = $wechat_pay->create($param['method']);

                    $data['pay_alipay'] = null;
                    $data['pay_wechat'] = $options;
                    return ['code' => 1, 'msg' => 'success', 'data' => $data];
                case "vip_integ":
                case "red_coin":
                case "chain_bean":
                case "love_bean":
                    if (md5($param['pay_password']) != $user->pay_password) {
                        return ['code' => -1, 'msg' => '支付密码错误'];
                    }
                    if ($user->assets->$account < $param['real_amount']) {
                        return ['code' => -1, 'msg' => '余额不足'];
                    }
                    return self::operations($info, $user, $account);
                default :
                    return ['code' => -1, 'msg' => '不支持的支付方式'];
            }

        }catch (\Exception $e){
            return ['code'=>-1, 'msg'=>$e->getMessage()];
        }
    }

    public static function operations($info, $user, $account): array
    {
        parent::startTrans();
        try {

            $info->pay_way = $account;
            $info->pay_state = 1;
            $info->pay_time = time();
            $info->status = 1;

            $info->save();

            if($user->level_video_id < $info->level_video_id){
                $user->level_video_id = $info->level_video_id;
                $user->save();
            }
            $user->assets->video_reward_surplus = roundNum($info->max_red_coin - $info->red_coin, 2);
            $user->assets->save();

            if (!in_array($account, ['wechat', 'alipay'])) {
                Account::getInstance()->basics($user->id, $account, $info->real_amount, '购买视频会员', '-')->createNormal($user->id);
            }
            Event::trigger('VideoReferrerAward', $info);
            parent::commit();
            return ['code' => 1, 'msg' => '支付成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getRedCoin($user, $video_red_coin, $type=1) :array
    {
        parent::startTrans();
        try{
            if(!$order = OrderVideo::where(['uid'=>$user->id,'status'=>1])->order('create_time', 'desc')->find()){
                return ['code'=>301, 'msg'=>'会员已过期，请及时充值'];
            }
            if($order->red_coin >= $order->max_red_coin){
                return ['code'=>301, 'msg'=>'您已获得了最高积分奖励'];
            }

            $is_max = 0;
            if($type == 1){
                if($order->red_coin + $video_red_coin > $order->max_red_coin){
                    $video_red_coin = round($order->max_red_coin - $order->red_coin);
                }

                Account::getInstance()->basics($user->id, 'red_coin', $video_red_coin, '看视频得积分', '+')->createNormal();
                $order->red_coin += $video_red_coin;
                $order->save();
                $order->red_coin >= $order->max_red_coin && $is_max = 1;

                $user->assets->video_reward_surplus = round($order->max_red_coin - $order->red_coin, 2);
                $user->assets->save();
            }
            parent::commit();
            return ['code'=>1, 'msg'=>'success', 'data'=>['is_max'=>$is_max, 'video_red_coin'=>$video_red_coin]];
        }catch (\Exception $e){
            parent::rollback();
            return ['code'=>-1, 'msg'=>$e->getMessage()];
        }
    }

}
